﻿using BLL;
using System;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Thksoft.Module.DataDetail
{
    public partial class ProjectFund : BaseUI.BasePage
    {
        #region 重构代码

        private Sys_CompanyBLL companyBLL = new Sys_CompanyBLL();
        private QS_PLANMONTHAPPLYBLL planMonthApplyBLL = new QS_PLANMONTHAPPLYBLL();
        private QS_PLANWEEKAPPLYBLL applyWeekBll = new QS_PLANWEEKAPPLYBLL();

        #endregion 重构代码

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                var applyType = ddlCheckType.Text;//项目资金类型
                //BindData1(0, 0, applyType);
            }
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            //var orderStr = ViewState["ORDER"] as string;
            //var orderTypeStr = ViewState["ORDER_TYPE"] as string;

            //获取公司
            var company = lognUser.USER_COMPANY.ToString();
            if (ddlCom.Value.ToString() != "-1")
            {
                company = ddlCom.Value.ToString();
            }

            DataTable apply = null;//资金流程
            var applyState = 0;//年月周

            //根据年月周判断资金计划流程
            var year = this.year.Text.Trim().ToString();
            var month = this.month.Text.Trim().ToString();
            var week = this.week.Text.Trim().ToString();
            if (week != "-1" && month != "-1" && year != "")
            {
                apply = applyWeekBll.BindSelectBy(year, month, week, company, 1, lognUser.USER_NAME);
                applyState = 3;//周
            }
            else if (month != "-1" && year != "")
            {
                apply = planMonthApplyBLL.GetDataByAppyId(Convert.ToInt32(company), Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(lognUser.USER_ID));
                applyState = 2;//月
            }
            else if (year != "")//年
            {
                MessageBox.Show(this, "还未有年资金计划详情附表的数据!");
                return;
            }
            else
            {
                MessageBox.Show(this, "请按照年月周依次选择！");
                return;
            }

            //资金流程申请ID
            decimal applyId = 0;
            if (ddlCom.Value.ToString() != "-1" && apply == null)
            {
                MessageBox.Show(this, "选择了公司，必须先选择业务日期！");
                return;
            }
            if (ddlCom.Value.ToString() != "-1" && apply.Rows.Count == 0)
            {
                MessageBox.Show(this, "当前条件此公司无数据！");
                return;
            }
            else if (apply != null && apply.Rows.Count != 0)
            {
                applyId = Convert.ToDecimal(apply.Rows[0][0].ToString());
            }

            //项目资金类型
            var applyType = ddlCheckType.Text;
            switch (applyType)
            {
                case "T1":
                    this.grvShow1.Visible = true;
                    this.grvShow2.Visible = false;
                    this.grvShow3.Visible = false;
                    this.grvShow6.Visible = false;
                    BindData1(applyId, applyState, applyType);
                    break;

                case "T2":
                    this.grvShow2.Visible = true;
                    this.grvShow1.Visible = false;
                    this.grvShow3.Visible = false;
                    this.grvShow6.Visible = false;
                    BindData2(applyId, applyState, applyType);
                    break;

                case "T3":
                case "T4":
                case "T5":
                    this.grvShow1.Visible = false;
                    this.grvShow2.Visible = false;
                    this.grvShow3.Visible = true;
                    this.grvShow6.Visible = false;
                    BindData3(applyId, applyState, applyType);
                    break;

                case "T6":
                    this.grvShow1.Visible = false;
                    this.grvShow2.Visible = false;
                    this.grvShow3.Visible = false;
                    this.grvShow6.Visible = true;
                    BindData6(applyId, applyState, applyType);
                    break;

                default:
                    break;
            }
        }

        //城市管网项目明细表(T6)
        public void BindData6(decimal applyId, decimal applyState, string applyType)
        {
            var sql = @"SELECT T1.C_VALUE2  AS C_VALUE1,
       T1.C_VALUE3  AS C_VALUE2,
       T1.C_VALUE4  AS C_VALUE3,
       T1.C_VALUE5  AS C_VALUE4,
       T1.C_VALUE6  AS C_VALUE5,
       T1.C_VALUE7  AS C_VALUE6,
       T1.C_VALUE8  AS C_VALUE7,
       T1.C_VALUE9  AS C_VALUE9,
       T1.C_VALUE10 AS C_VALUE12,
       T1.C_VALUE11 AS C_VALUE13
  FROM QS_PLAN_DETAILS T1
 WHERE 1=1";
            if (applyId != 0)
            {
                sql += " AND T1.N_PLAN_ID=" + applyId;
            }
            if (applyState != 0)
            {
                sql += " AND T1.N_STATE=" + applyState;
            }
            sql += " AND T1.C_VALUE1='" + applyType + "'";
            sql += " ORDER BY T1.C_VALUE1";
            DataTable dt = new BaseBLL().Query(sql);

            var row = dt.NewRow();
            row["C_VALUE1"] = DBNull.Value;
            row["C_VALUE2"] = "合计";
            row["C_VALUE3"] = DBNull.Value;
            row["C_VALUE4"] = DBNull.Value;
            row["C_VALUE5"] = DBNull.Value;
            row["C_VALUE6"] = dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["C_VALUE6"]));
            row["C_VALUE7"] = dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["C_VALUE7"]));
            row["C_VALUE9"] = dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["C_VALUE9"]));
            row["C_VALUE12"] = DBNull.Value;
            row["C_VALUE13"] = DBNull.Value;
            dt.Rows.Add(row);
            grvShow6.DataSource = dt;
            grvShow6.DataBind();
        }

        //T3、T4、T5
        public void BindData3(decimal applyId, decimal applyState, string applyType)
        {
            var sql = @"SELECT T1.C_VALUE2  AS C_VALUE1,
       T1.C_VALUE3  AS C_VALUE2,
       T1.C_VALUE4  AS C_VALUE3,
       T1.C_VALUE5  AS C_VALUE4,
       T1.C_VALUE6  AS C_VALUE5,
       T1.C_VALUE7  AS C_VALUE6,
       T1.C_VALUE8  AS C_VALUE7,
       T1.C_VALUE9  AS C_VALUE9,
       T1.C_VALUE10 AS C_VALUE12,
       T1.C_VALUE11 AS C_VALUE13
  FROM QS_PLAN_DETAILS T1
 WHERE 1=1";
            if (applyId != 0)
            {
                sql += " AND T1.N_PLAN_ID=" + applyId;
            }
            if (applyState != 0)
            {
                sql += " AND T1.N_STATE=" + applyState;
            }
            sql += " AND T1.C_VALUE1='" + applyType + "'";
            sql += " ORDER BY T1.C_VALUE1";
            DataTable dt = new BaseBLL().Query(sql);

            var row = dt.NewRow();
            row["C_VALUE1"] = DBNull.Value;
            row["C_VALUE2"] = "合计";
            row["C_VALUE3"] = DBNull.Value;
            row["C_VALUE5"] = DBNull.Value;
            row["C_VALUE6"] = dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["C_VALUE6"]));
            row["C_VALUE7"] = dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["C_VALUE7"]));
            row["C_VALUE9"] = dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["C_VALUE9"]));
            row["C_VALUE12"] = DBNull.Value;
            row["C_VALUE13"] = DBNull.Value;
            dt.Rows.Add(row);
            grvShow3.DataSource = dt;
            grvShow3.DataBind();
        }

        //天然气购入明细表(T2)
        public void BindData2(decimal applyId, decimal applyState, string applyType)
        {
            var sql = @"SELECT T1.C_VALUE2 AS C_VALUE1,
       T1.C_VALUE3 AS C_VALUE2,
       T1.C_VALUE4 AS C_VALUE3,
       T1.C_VALUE5 AS C_VALUE4,
       T1.C_VALUE6 AS C_VALUE5,
       T1.C_VALUE7 AS C_VALUE6,
       T1.C_VALUE8 AS C_VALUE7
  FROM QS_PLAN_DETAILS T1
 WHERE 1=1";
            if (applyId != 0)
            {
                sql += " AND T1.N_PLAN_ID=" + applyId;
            }
            if (applyState != 0)
            {
                sql += " AND T1.N_STATE=" + applyState;
            }
            sql += " AND T1.C_VALUE1='" + applyType + "'";
            sql += " ORDER BY T1.C_VALUE2";
            DataTable dt = new BaseBLL().Query(sql);

            var row = dt.NewRow();
            row["C_VALUE1"] = "合计";
            row["C_VALUE2"] = DBNull.Value;
            row["C_VALUE3"] = DBNull.Value;
            row["C_VALUE4"] = DBNull.Value;
            row["C_VALUE5"] = dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["C_VALUE5"]));
            row["C_VALUE6"] = DBNull.Value;
            row["C_VALUE7"] = DBNull.Value;
            dt.Rows.Add(row);
            grvShow2.DataSource = dt;
            grvShow2.DataBind();
        }

        //主营业务收入明细表(T1)
        public void BindData1(decimal applyId, decimal applyState, string applyType)
        {
            var sql = "SELECT T1.C_VALUE2 AS C_INDEX,T1.C_VALUE3 AS C_NAME,T1.C_VALUE4 AS SaleNumber,T1.C_VALUE5 AS UnitePrice,T1.C_VALUE6 AS SumPrice,T1.C_VALUE7 AS Flow,T1.C_VALUE8 AS Remark,T1.C_VALUE9 AS ParentIndex FROM QS_PLAN_DETAILS T1 WHERE 1=1";
            if (applyId != 0)
            {
                sql += " AND T1.N_PLAN_ID=" + applyId;
            }
            if (applyState != 0)
            {
                sql += " AND T1.N_STATE=" + applyState;
            }
            sql += " AND T1.C_VALUE1='" + applyType + "'";
            sql += " ORDER BY T1.C_VALUE2";
            DataTable dt = new BaseBLL().Query(sql);

            grvShow1.DataSource = dt;
            grvShow1.DataBind();
        }

        protected void grvShow_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "cu=style.backgroundColor;style.backgroundColor='#d5e7ff'");
                e.Row.Attributes.Add("onmouseout", "style.backgroundColor=cu");
                if (e.Row.RowIndex % 2 == 0)
                {
                    e.Row.Style.Add(HtmlTextWriterStyle.BackgroundColor, "#FFFFFF");
                }
                else
                {
                    e.Row.Style.Add(HtmlTextWriterStyle.BackgroundColor, "#EAFFFF");
                }
            }
        }

        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvShow1_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sPage = e.SortExpression;
            string SortOrder, OrderDire;
            SortOrder = ViewState["ORDER"] == null ? null : (string)ViewState["ORDER"];
            OrderDire = ViewState["ORDER_TYPE"] == null ? null : (string)ViewState["ORDER_TYPE"];
            if (SortOrder == sPage)
            {
                if (OrderDire == "DESC")
                    OrderDire = "ASC";
                else
                    OrderDire = "DESC";
            }
            else
            {
                SortOrder = e.SortExpression;
                OrderDire = "ASC";
            }
            ViewState["ORDER"] = SortOrder;
            ViewState["ORDER_TYPE"] = OrderDire;
            btnSelect_Click(sender, e);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            var orderStr = ViewState["ORDER"] as string;
            var orderTypeStr = ViewState["ORDER_TYPE"] as string;

            //if (ddlCheckDate.Text == "")
            //{
            //    MessageBox.Show(Page, "【系统提示】未能查询出数据，暂时不能导出，请先查询数据。");
            //    return;
            //}
            int year = 0;//int.Parse(ddlCheckDate.Text.Substring(0, 4));
            decimal comid = lognUser.USER_COMPANY;
            if (ddlCom.Value != -1)
            {
                comid = ddlCom.Value;
            }
            var comidStr = companyBLL.GetCompanyFatherAndChildByID(comid);

            var sql = @"SELECT
	T1.N_MONTHAPP_ID,
	T1.N_BUSINESS_ID,
	T2.CMY_NAME,
	T1.C_MONTH_NAME,
	T1.N_MONTH,
	SUM(decode(T4.N_TYPE2,1,T3.N_AMOUNT,0)) INTO_SUM,
	SUM(decode(T4.N_TYPE2,2,T3.N_AMOUNT,0)) OUT_SUM
FROM QS_PLANMONTHAPPLY T1
INNER JOIN SYS_COMPANY T2
ON T1.N_COMPANY_ID = T2.CMY_ID
INNER JOIN QS_PLANMONTH_DETAIL T3
ON T1.N_MONTHAPP_ID = T3.N_MONTHAPP_ID
INNER JOIN QS_PROJECT T4
ON T3.N_PROID = T4.N_PROID
WHERE T1.N_COMPANY_ID IN ({0}) AND T1.N_TYPE=2 {1}
GROUP BY
	T1.N_MONTHAPP_ID,
	T1.N_BUSINESS_ID,
	T2.CMY_NAME,
	T1.C_MONTH_NAME,
	T1.N_MONTH "; //T1.N_MONTH

            if (orderStr != null)
            {
                sql += " ORDER BY " + orderStr + " " + orderTypeStr;
            }

            sql = "";//string.Format(sql, comidStr, "AND T1.N_YEAR = " + year);

            DataTable dt = planMonthApplyBLL.Query(sql);

            var html = "<table>";
            html += "<tr>";
            html += "<th>公司名称</th>";
            html += "<th>业务名称</th>";
            html += "<th>月数</th>";
            html += "<th>合计（流入）</th>";
            html += "<th>合计（流出）</th>";
            html += "</tr>";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i % 2 == 0)
                {
                    html += "<tr style=\"background-color:#EAFFFF;\">";
                }
                else
                {
                    html += "<tr>";
                }
                html += "<td>" + dt.Rows[i]["CMY_NAME"].ToString() + "</td>";
                html += "<td>" + dt.Rows[i]["C_MONTH_NAME"].ToString() + "</td>";
                html += "<td>" + dt.Rows[i]["N_MONTH"].ToString() + "</td>";
                html += "<td>" + dt.Rows[i]["INTO_SUM"].ToString() + "</td>";
                html += "<td>" + dt.Rows[i]["OUT_SUM"].ToString() + "</td>";
                html += "</tr>";
            }

            html += "<tr>";
            html += "<td colspan=\"3\" align=\"center\">合计</td>";
            html += "<td>" + dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["INTO_SUM"])) + "</td>";
            html += "<td>" + dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["OUT_SUM"])) + "</td>";
            html += "<td></td>";
            html += "</tr>";
            html += "</table>";
            //toExecl1(html, (ddlCheckDate.Text == "" ? "" : ddlCheckDate.Text + "月") + "资金明细");
        }
    }
}